<?php

namespace app\store\service\game;

use app\common\service\BaseService;
use app\store\model\game\Category as CaregoryModel;
use app\store\model\game\Game as GameModel;

class Category extends BaseService
{
    public function getList($params):array
    {
        $condition = [];
        if(!empty($params['name'])){
            $condition[] = ['name', 'like', "%{$params['name']}%"];
        }
        $condition[] = ['is_del','=',0];
        return (new CaregoryModel())
            ->where($condition)
            ->order('sort','DESC')
            ->paginate($params['limit'] ?? 15)
            ->toArray();
    }

    /**
     * @param $params
     */
    public function save($params): bool
    {
        if(!empty($params['id'])){
            $condition = [
                ['is_del','=',0],
                ['id','=',$params['id']]
            ];
            $cate = (new CaregoryModel())->where($condition)->find();
            if(!$cate) throwError('该分类已被删除或不存在');
            $cate->name = $params['name'];
            $cate->desc = $params['desc'] ?? '';
            $cate->sort = $params['sort'] ?? 100;
            return $cate->save();
        }else{
            $cate = (new CaregoryModel())::create([
                'name' => $params['name'],
                'desc' => $params['desc'] ?? '',
                'sort' => $params['sort'] ?? 100,
            ]);
            if(!$cate->id){
                throwError('新增异常');
            }
            return true;
        }
    }

    /**删除
     * @param $params
     */
    public function delete($id): bool
    {
        $condition = [
            ['is_del','=',0],
            ['id','=',$id]
        ];
        $cate = (new CaregoryModel())->where($condition)->find();
        if(!$cate) throwError('该分类已被删除或不存在');
        //查看是否有活动使用分类
        $condition = [
            ['category_id','=',$id],
            ['is_del','=',0]
        ];
        $find = (new GameModel())->where($condition)->find();
        if($find){
            throwError('该分类正在被使用,请勿删除');
        }
        $cate->is_del = 1;
        return $cate->save();
    }
}